import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  Query,
  Request,
} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
import { DeptService } from './dept.service';
import { CreateDeptDto } from './dto/create-dept.dto';
import { DeptQuery } from './dto/query-dept.dto';
import { UpdateDeptDto } from './dto/update-dept.dto';

@ApiTags('部门管理')
@Controller('dept')
export class DeptController {
  constructor(private readonly deptService: DeptService) {}

  @Post()
  @ApiOperation({ summary: '创建部门' })
  create(@Body() createDeptDto: CreateDeptDto) {
    // TODO: 从请求上下文中获取当前登录用户ID
    const userId = 1; // 示例，实际应从JWT或会话中获取
    return this.deptService.create(createDeptDto, userId);
  }

  @Get('tree')
  @ApiOperation({ summary: '获取部门树' })
  findTree() {
    return this.deptService.findTree();
  }

  @Get('list')
  @ApiOperation({ summary: '分页查询部门列表' })
  findByPage(@Query() query: DeptQuery) {
    return this.deptService.findByPage(query);
  }

  @Get('options')
  @ApiOperation({ summary: '获取部门下拉选项树' })
  async getDeptOptions() {
    const data = await this.deptService.getDeptOptions();
    return data;
  }

  @Get(':id')
  @ApiOperation({ summary: '根据ID获取部门详情' })
  findOne(@Param('id') id: string) {
    return this.deptService.findById(+id);
  }

  @Patch(':id')
  @ApiOperation({ summary: '更新部门' })
  update(
    @Param('id') id: string,
    @Body() updateDeptDto: UpdateDeptDto,
    @Request() req,
  ) {
    const userId = req.user.id;
    updateDeptDto.id = +id;
    return this.deptService.update(updateDeptDto, userId);
  }

  @Delete(':id')
  @ApiOperation({ summary: '删除部门及其所有子部门' })
  remove(@Param('id') id: string, @Request() req) {
    const userId = req.user.id;
    return this.deptService.remove(+id, userId);
  }
}
